package com.zto.mybatis.interceptor;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import javax.sound.midi.SysexMessage;
import java.util.Properties;

/**
 * Created by xingyuchao on 2017-07-02.
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class SqlInterceptor implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement statement = (MappedStatement) invocation.getArgs()[0]; //获取的是args参数MappedStatement，

        BoundSql boundSql = statement.getBoundSql(invocation.getArgs()[1]);


        System.err.println("sql:"+boundSql.getSql());//打印sql语句
        System.err.println("params:"+boundSql.getParameterObject());//打印参数.
        //通过invocation.proceed()方法完成调用链的推进
        return invocation.proceed();
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    //用于设置额外的参数，参数配置在拦截器的Properties节点里。
    public void setProperties(Properties properties) {
        Object name = properties.get("name");
        System.err.println(name);
    }
}
